package controller

import (
	"encoding/json"
	"io"
	"net/http"
	"poker/db"
	"poker/model"
	"poker/utils"
	"time"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
)

func GetOpenid(c *gin.Context) {
	// 从请求中获取参数
	code := c.Query("code")
	if code == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "code is required"})
		return
	}

	// 获取渠道参数
	channel := c.Param("channel")
	if channel == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "channel is required"})
		return
	}

	var (
		appID     string
		appSecret string
	)

	// 根据渠道参数调整逻辑
	switch channel {
	case "wx":
		// 微信渠道
		appID = "your_wx_app_id"
		appSecret = "your_wx_app_secret"
	case "ks":
		// 快手渠道
		appID = "your_ks_app_id"
		appSecret = "your_ks_app_secret"
	case "tt":
		// 抖音渠道
		appID = "your_tt_app_id"
		appSecret = "your_tt_app_secret"
	default:
		c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported channel"})
		return
	}

	// 构造 API 请求
	apiURL := "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appID +
		"&secret=" + appSecret +
		"&code=" + code +
		"&grant_type=authorization_code"

	// 发起 HTTP 请求
	resp, err := http.Get(apiURL)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to call API"})
		return
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read response"})
		return
	}

	// 解析响应内容
	var result map[string]interface{}
	if err := json.Unmarshal(body, &result); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to parse response"})
		return
	}

	// 检查是否有错误
	if _, ok := result["errcode"]; ok {
		c.JSON(http.StatusInternalServerError, gin.H{"error": result["errmsg"]})
		return
	}

	// 提取 OpenID
	openID := result["openid"].(string)
	if openID == "" {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "OpenID not found"})
		return
	}

	// 返回 OpenID 和渠道信息
	c.JSON(http.StatusOK, gin.H{
		"openid":  openID,
		"channel": channel,
	})
}

func Login(c *gin.Context) {
	// channel := c.Param("channel")
	user := &model.User{}
	db.FindOne("user", bson.M{"name": "AI2502210953421"}, user)
	c.JSON(200, gin.H{"user": user})
}

func UpLoad(c *gin.Context) {
	var user model.User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	channel := c.Param("channel")
	auth := utils.GenerateAuth(user.Uid + user.Data + channel)
	col := channel + "_user"
	// 检查认证信息（这里只是简单示例，实际中需要更复杂的认证逻辑）
	if user.Auth != auth {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid auth"})
		return
	}

	user.UpdateDate = time.Now().Format("2006/01/02 15:04:05")
	// 存储用户数据（忽略 Auth 字段）
	filter := bson.M{"_id": user.Uid}
	if err := user.Save(col, filter); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save user data"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "User data uploaded successfully"})
}

func GetUserData(c *gin.Context) {
	channel := c.Param("channel")
	uid := c.Param("id")
	col := channel + "_user"

	user := &model.User{Uid: uid}
	filter := bson.M{"_id": user.Uid}
	// 调用 FindOne 方法查询用户数据
	if err := user.FindOne(col, filter); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"uid":  user.Uid,
			"data": "",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"uid":  user.Uid,
		"data": user.Data,
	})
}
